from flask import Blueprint, jsonify, request, json
import orgMgmt.orgOperation.subcomOprt as subcomOprt
from L_TMgmt.L_TOperation import stationOprt

station = Blueprint('station', __name__)


@station.route('/', methods=['GET'])
def index():
    subcomOprt.hello()
    print("here is station")
    return jsonify('stationnnnnn')


# ###########################################################################################################登录
@station.route('/init', methods=['GET'])
def init():
    if stationOprt.getAllStation() == 0:
        # 待测试
        return subcomOprt.getAllSubcom()
    else:
        stationlist = []
        for line in stationOprt.getAllStation():
            stationlist.append({"station_id": line[0], "station_name": line[1],
                               "attr_line_id": line[2], "attr_line_name": line[3]})
        print(stationlist)
    return jsonify(stationlist)


@station.route('/newstation', methods=['POST'])
def newstation():
    print("new a station")
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))
    print(json_data)

    if stationOprt.newstation(json_data.get('station_name'), json_data.get('attr_line_id')):
        return jsonify(1)
    else:
        return jsonify(2)


@station.route('/editstation', methods=['POST'])
def editstation():
    print("edit a station")
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))
    print(json_data)

    if stationOprt.editstation(json_data.get('station_id'), json_data.get('station_name'), json_data.get('attr_line_id')):
        return jsonify(1)
    else:
        return jsonify(2)


@station.route('/select', methods=['POST'])
def stationVagueSelect():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    word = json_data.get('word')
    stationlist = []
    if stationOprt.searchStation(word) == 0:
        return jsonify(0)
    else:
        for line in stationOprt.searchStation(word) :
            stationlist.append({"station_id": line[0], "station_name": line[1],
                               "attr_line_id": line[2], "attr_line_name": line[3]})
    print(stationlist)
    return jsonify(stationlist)


@station.route('/delete', methods=['POST'])
def stationDelete():
    data = request.get_data()
    print(data)
    word = data.decode("utf-8")
    print(word)

    check = stationOprt.checkdelete(word)
    if check != '':
        return jsonify(check)

    if stationOprt.deleteStation(word):
        return jsonify(1)
    else:
        return jsonify(2)


@station.route('/options', methods=['GET'])
def options():
    print("to get options")
    if stationOprt.getOptions() == 0:
        return jsonify(0)  # 待测试
    else:
        linelist = []
        for line in stationOprt.getOptions():
            linelist.append({'value': line[0], 'label': line[1]})
        print(linelist)
    return jsonify(linelist)
